import React from 'react';
import { Form, Input, InputNumber, Popover, Typography, message, Empty } from 'antd';
import { get as getPath } from 'object-path';
import CityPicker from '@/components/CityPicker';
import { getCompanyDetail, getRelativeOrganizations } from '../../services';
import styles from './index.less';

const { TextArea } = Input;
const Company = ({ form, isAddPage, query, setLoading }) => {
    const { getFieldDecorator } = form;
    const [info, setInfo] = React.useState(null);
    const [relativeList, setRelativeList] = React.useState([]);
    // const [logoFileArr, setLogoFileArr] = React.useState([]);

    const orgTitle = getPath(info, 'organizationType', '') === 1 ? '集团' : '公司';

    const getDetail = async () => {
        setLoading(true);
        const res = await getCompanyDetail(query && query.organizationCode);
        const { data, code } = res;
        if (code === 10000) {
            // console.log(data);
            setInfo(data);
            // const logo = getPath(data, 'logoFile', []);
            // if (logo && logo.length > 0) {
            //     setLogoFileArr([
            //         {
            //             uid: logo[0].keyName,
            //             keyName: logo[0].keyName,
            //             name: logo[0].originName,
            //             oldName: logo[0].originName,
            //             url: logo[0].url
            //         }
            //     ]);
            // }
        }
        setLoading(false);
    };

    const getRelativeList = async orgCode => {
        if (!orgCode) {
            return;
        }
        setLoading(true);
        const res = await getRelativeOrganizations(orgCode);
        const { data, code, msg } = res;
        if (code === 10000) {
            // console.log(data);
            setRelativeList((Array.isArray(data) && data) || []);
        } else {
            message.error(msg);
        }
        setLoading(false);
    };

    React.useEffect(() => {
        if (!isAddPage && query) {
            getDetail();
        }
        if (isAddPage && query) {
            getRelativeList(query && query.organizationCode);
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [query]);

    React.useEffect(() => {
        if (!isAddPage && info && getPath(info, 'organizationType', '') !== 1) {
            getRelativeList(getPath(info, 'parentOrganizationCode', ''));
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [info]);

    const getArea = () => {
        const str = getPath(info, 'area', '');
        if (str) {
            return str.split(',');
        }
        return undefined;
    };

    const popoverContent = (
        <div style={{ minWidth: 250, maxWidth: 500, maxHeight: 250, overflow: 'auto' }}>
            {relativeList.map(item => (
                <div key={item.organizationCode} style={{ display: 'flex', justifyContent: 'space-between' }}>
                    <Typography.Paragraph ellipsis>{item.organizationName}</Typography.Paragraph>
                    <div style={{ marginLeft: 10, marginRight: 10, flexShrink: 0, width: '6em' }}>
                        排序号：{item.sort}
                    </div>
                </div>
            ))}
            {relativeList.length <= 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
        </div>
    );

    const parentForm = (
        <>
            <Form.Item label="上级机构">
                {isAddPage ? getPath(query, 'organizationName', '') : getPath(info, 'parentOrganizationName', '')}
            </Form.Item>
            <Form.Item label="国家/地区">
                {getFieldDecorator('area', {
                    initialValue: getArea(),
                    rules: [
                        {
                            required: true,
                            message: '国家/地区不能为空'
                        }
                    ]
                })(<CityPicker valueType="codeArray" showSearch placeholder="请选择国家/地区" />)}
            </Form.Item>
        </>
    );

    const nameForm = (
        <>
            <Form.Item label={`${orgTitle}名称(中文)`}>
                {getFieldDecorator('organizationName', {
                    initialValue: getPath(info, 'organizationName', ''),
                    rules: [
                        {
                            required: true,
                            message: `${orgTitle}名称(中文)不能为空`,
                            whitespace: true
                        },
                        {
                            validator(_, value, callback) {
                                if (value.indexOf('/') > -1 || value.indexOf(':') > -1) {
                                    callback('不允许输入:或/');
                                } else {
                                    callback();
                                }
                            }
                        }
                    ]
                })(<Input placeholder={`请输入${orgTitle}名称(中文)`} allowClear maxLength={150} />)}
            </Form.Item>
            <Form.Item label={`${orgTitle}名称(英文)`}>
                {getFieldDecorator('organizationNameEnglish', {
                    initialValue: getPath(info, 'organizationNameEnglish', ''),
                    rules: [
                        {
                            validator(_, value, callback) {
                                if (value.indexOf('/') > -1 || value.indexOf(':') > -1) {
                                    callback('不允许输入:或/');
                                } else {
                                    callback();
                                }
                            }
                        }
                    ]
                })(<Input placeholder={`请输入${orgTitle}名称(英文)`} allowClear maxLength={150} />)}
            </Form.Item>
            <Form.Item label="排序号">
                <Popover
                    content={popoverContent}
                    title="当前排序"
                    trigger="focus"
                    placement="bottomRight"
                    getPopupContainer={trigger => trigger.parentNode}
                >
                    {getFieldDecorator('sort', {
                        initialValue: getPath(info, 'sort', ''),
                        rules: [
                            {
                                required: true,
                                message: '排序号不能为空'
                            }
                        ]
                    })(
                        <InputNumber
                            min={1}
                            max={999}
                            precision={0}
                            placeholder="请输入排序号"
                            style={{ width: '100%' }}
                        />
                    )}
                </Popover>
            </Form.Item>
        </>
    );

    return (
        <Form className={styles.formWrap}>
            {isAddPage ? (
                <>
                    {parentForm}
                    {nameForm}
                </>
            ) : (
                <>
                    {nameForm}
                    {parentForm}
                </>
            )}
            <Form.Item label={`${orgTitle}简介(中文)`}>
                {getFieldDecorator('organizationDesc', {
                    initialValue: getPath(info, 'organizationDesc', '')
                })(
                    <TextArea
                        placeholder={`请输入${orgTitle}简介(中文)`}
                        autosize={{ minRows: 3, maxRows: 6 }}
                        maxLength={800}
                    />
                )}
            </Form.Item>
            <Form.Item label={`${orgTitle}简介(英文)`}>
                {getFieldDecorator('organizationDescEnglish', {
                    initialValue: getPath(info, 'organizationDescEnglish', '')
                })(
                    <TextArea
                        placeholder={`请输入${orgTitle}简介(英文)`}
                        autosize={{ minRows: 3, maxRows: 6 }}
                        maxLength={800}
                    />
                )}
            </Form.Item>
            {/* <Form.Item label={`${orgTitle}logo`} style={{ marginBottom: 0, minHeight: 130 }}>
                {getFieldDecorator('organizationLogo', {
                    initialValue:
                        logoFileArr && logoFileArr.length > 0 ? { allFileList: logoFileArr } : { allFileList: [] }
                })(
                    <FileUpload
                        isSingle
                        categoryCode="logoFile"
                        checkFileType="JPG,JPEG,BMP,GIF,PNG"
                        checkFileTypeMsg="只能上传JPG,JPEG,BMP,GIF,PNG格式的文件！"
                    />
                )}
            </Form.Item> */}
        </Form>
    );
};

export default Company;
